package com.bluelinelabs.logansquare.data;

import com.bluelinelabs.logansquare.ResourceTable;
import com.bluelinelabs.logansquare.model.User;

import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;
/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * list 适配器
 */
public class ListAdapter extends RecycleItemProvider {
    private List<User> datas;
    private Context context;

    public ListAdapter(Context context, List<User> data) {
        this.context = context;
        datas = new ArrayList<>();
    }

    public void setData(List<User> data) {
        this.datas.addAll(data);
        notifyDataChanged();
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Component getComponent(int position, Component convertView, ComponentContainer parent) {
        Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_list_item, null, false);
        if (!(component instanceof ComponentContainer)) {
            return null;
        }
        ComponentContainer rootLayout = (ComponentContainer) component;
        User user = datas.get(position);

        Text id = (Text) rootLayout.findComponentById(ResourceTable.Id_uid);
        id.setText(String.valueOf(position + 1));

        Text name = (Text) rootLayout.findComponentById(ResourceTable.Id_name);
        name.setText("姓名:" + user.name == null ? "LoganSquare" : user.name.first + user.name.last);

        Text age = (Text) rootLayout.findComponentById(ResourceTable.Id_age);
        age.setText("年龄:" + user.age + "");

        Text addr = (Text) rootLayout.findComponentById(ResourceTable.Id_addr);
        addr.setText("地址:" + user.address);

        Text lat = (Text) rootLayout.findComponentById(ResourceTable.Id_lat);
        lat.setText("经纬度:" + String.valueOf(user.latitude) + "-" + String.valueOf(user.longitude));

        return component;
    }
}
